package io.renren.modules.medical.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.renren.common.exception.MedicalException;
import io.renren.common.result.ResultCodeEnum;
import io.renren.common.utils.DoctorInfoUtils;
import io.renren.common.utils.PageUtils;
import io.renren.modules.medical.entity.DoctorInfoEntity;
import io.renren.modules.medical.service.DoctorInfoService;
import io.renren.modules.medical.service.OnlineChatService;
import io.renren.modules.medical.service.PatientInfoService;
import io.renren.modules.medical.service.WebSocketInterService;
import io.renren.modules.medical.vo.weixinVo.ApiChatHistory;
import io.renren.modules.medical.vo.weixinVo.ApiChatListVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author Luo Sheng
 * @school YiBin university
 * @create 2023-04-18 15:14
 */
@RequiredArgsConstructor
@Service("onlineChatService")
public class OnlineChatServiceImpl implements OnlineChatService {
    private final PatientInfoService patientInfoService;

    private final DoctorInfoService doctorInfoService;

    private final WebSocketInterService webSocketInterService;


    @Override
    public PageUtils queryPageByUserId(Map<String, Object> params) {
        return patientInfoService.queryPageByUserId(params);
    }

    /**
     * 获取聊天集合
     */
    @Override
    public List<ApiChatListVo> getChatList(Long subId) {
        if (subId == null) {
            throw new MedicalException(ResultCodeEnum.HEALTH_GUIDANCE_ERROR.getCode(), "传入参数为null");
        }
        // TODO 登陆模块再修改获取wxUserId的逻辑
        Long patientId = 1L;

        // 医生list
        LambdaQueryWrapper<DoctorInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        List<DoctorInfoEntity> list;
        if (subId.equals(0L)) {
            list = doctorInfoService.list();
        } else {
            queryWrapper.eq(DoctorInfoEntity::getDepId, subId);
            list = doctorInfoService.list(queryWrapper);
        }
        // 遍历封装
        List<ApiChatListVo> apiChatListVos = list.stream().map(doctorInfoEntity -> {
            ApiChatListVo apiChatListVo = new ApiChatListVo();
            BeanUtils.copyProperties(doctorInfoEntity, apiChatListVo);
            // 获取未查看的消息记录(医生发给病人的)
            Integer noneVisitCount = webSocketInterService.getNoneVisitCount(doctorInfoEntity.getId(), patientId);
            // 获取医生姓并封装进apiChatListVo
            String firstName = doctorInfoEntity.getName().substring(0, 1);
            apiChatListVo.setFirstName(firstName);
            apiChatListVo.setNoneVisitCount(noneVisitCount);
            apiChatListVo.setSubId(doctorInfoEntity.getDepId());
            return apiChatListVo;
        }).collect(Collectors.toList());

        // 最终封装进List<ApiChatListVo>

        return apiChatListVos;

    }


    /**
     * 根据输入参数查询得到List<ApiChatListVo>
     *
     */
    @Override
    public List<ApiChatListVo> search(Map<String, Object> params) {
        String key = (String) params.get("key");
        String pattern = ".*" + key + ".*";

        // 先得到最初的list集合
        List<ApiChatListVo> apiChatListVos = this.getChatList(0L);
        // 通过正则表达式来过滤得到最终值
        List<ApiChatListVo> collect = apiChatListVos.stream()
                .filter(item -> Pattern.matches(pattern, item.getName())
                        || Pattern.matches(pattern, item.getDescription())
                ).collect(Collectors.toList());
        return collect;
    }

    /**
     * 获取发送消息历史
     *
     */
    @Override
    public List<ApiChatHistory> history(Map<String, Object> params) {
        Map<String, Long> paramObj = getParamObj(params);

        // 通过浏览器传参在本地获取到用户信息
        // TODO 登陆模块再修改获取wxUserId的逻辑
        Long sendId = 1L;
        // 获取当前微信用户关联信息
        List<ApiChatHistory> apiChatHistoryList = webSocketInterService
                .getHistory((paramObj.get("page") - 1) * paramObj.get("limit"),
                        paramObj.get("limit"), sendId, paramObj.get("sendToId"));
        // 当前微信用户是病人，直接从医生表中获取头像
        DoctorInfoEntity doctorInfoEntity = doctorInfoService.getById(paramObj.get("sendToId"));
        // 封装avatar和identity
        apiChatHistoryList.stream().peek(item -> {
            if (item.getSendId().equals(sendId)) {
                // 如果发送者Id == 当前用户信息的id
                item.setIdentity(1);
                // 设置头像为发送者头像
            } else {
                // 设置设置身份为被发送者
                item.setIdentity(0);
                // 设置头像为被发送者头像
            }
        }).collect(Collectors.toList());

        return apiChatHistoryList;
    }

    @Override
    public List<ApiChatHistory> historyToMedical(Map<String, Object> params) {
        Map<String, Long> paramObj = getParamObj(params);
        Long sendId = DoctorInfoUtils.getDoctorInfo(doctorInfoService).getId();
        List<ApiChatHistory> apiChatHistoryList = webSocketInterService
                .getHistory((paramObj.get("page") - 1) * paramObj.get("limit"),
                        paramObj.get("limit"), sendId, paramObj.get("sendToId"));

        apiChatHistoryList.stream().peek(item -> {
            if (item.getSendId().equals(sendId)) {
                // 如果发送者Id == 当前用户信息的id
                item.setIdentity(1);
            } else {
                // 设置设置身份为被发送者
                item.setIdentity(0);
            }
        }).collect(Collectors.toList());

        return apiChatHistoryList;
    }

    @Override
    public void clearNoneVisit(Long sendId, Long sendToId) {
        Integer count = webSocketInterService.clearNoneVisit(sendId, sendToId);
    }

    private Map<String, Long> getParamObj(Map<String, Object> params) {
        String param1 = (String) params.get("sendToId");
        String param2 = (String) params.get("page");
        String param3 = (String) params.get("limit");
        long sendToId = param1 != null ? Long.parseLong(param1) : 0;
        long page = param2 != null ? Long.parseLong(param2) : 0;
        long limit = param3 != null ? Long.parseLong(param3) : 0;
        HashMap<String, Long> map;
        map = new HashMap<String, Long>();
        map.put("sendToId", sendToId);
        map.put("page", page);
        map.put("limit", limit);
        return map;
    }
}
